import { cloneDeep } from "lodash-es";
import { isEmpty } from "@/utils/validate";


/*
 $name 通用的递归组件
 $author xhcss
 @data 需要递归的数组
 @parentId 递归的父级id
 @parentName 递归的父级的key
 @id 本级的key
 @nonull 是否删除children=[] 空的对象，默认删除
*/
export function generalRecursion(
  data: any[],
  parentId: any = null,
  parentName: string = "parentId",
  id: string = "id",
  nonull: boolean = true,
  childrenName: string = "children"
): any[] {
  if (!Array.isArray(data) || data.length == 0) return [];
  data = cloneDeep(data);
  return data
    .filter((o) => o[parentName] == parentId)
    .map((v) => {
      v[childrenName] = generalRecursion(
        data,
        v[id],
        parentName,
        id,
        nonull,
        childrenName
      );
      nonull && isEmpty(v[childrenName]) ? delete v[childrenName] : v;
      return v;
    });
}
